package com.tanguy.user.utlis.pay

import android.content.Context
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import com.tanguy.user.App.Companion.app
import com.tanguy.user.Const
import com.tanguy.user.R
import com.tanguy.user.base.BasePopupWindow
import cn.sinata.xldutils_kotlin.utils.SpanBuilder
import com.tanguy.user.net.http.HttpManager
import com.tanguy.user.utlis.extend.*
import org.jetbrains.anko.find
import org.json.JSONObject

/**
 * Created by dab on 2017/11/22 0022 17:15
 * 返回的code:0成功1失败2取消3.确认中
 */
class PayWindow(val context: Context, val money: Double, val orderID: String, val back: (code: Int, type: Int) -> Unit) : BasePopupWindow(context) {
    override fun setContentRes(): Int = R.layout.window_pay
    private var payType=0 //0 余额 1微信 2支付宝
    private var dismissByBack=true //是不是自己取消(返回键和取消)
    override fun initView(view: View) {
        super.initView(view)
        view.apply {
            setText(R.id.tv_money,"支付￥${money.toReserveDecimal(2)}")
            setText(R.id.tv_balance,initText("余额支付\n使用余额快捷支付",0,4))
            setText(R.id.tv_weixin,initText("微信支付\n使用微信快捷支付",0,4))
            setText(R.id.tv_zfb,initText("支付宝支付\n使用支付宝快捷支付",0,5))

            click(R.id.iv_close){
                dismissByBack=true
                dismiss()
            }

            click(R.id.tv_balance){
                if (payType==0)return@click
                payType=0
                refreshUI(view)
            }
            click(R.id.tv_weixin){
                if (payType==1)return@click
                payType=1
                refreshUI(view)
            }
            click(R.id.tv_zfb){
                if (payType==2)return@click
                payType=2
                refreshUI(view)
            }
            click(R.id.tv_confirm){
                pay(payType)
            }
        }
    }

    private fun refreshUI(view: View) {
        view.apply {
            find<TextView>(R.id.tv_balance).setDrawable(left = R.mipmap.yue,right =if (payType==0)R.mipmap.xuanzhong_1 else R.mipmap.rbtn_green_normal)
            find<TextView>(R.id.tv_weixin).setDrawable(left = R.mipmap.weixin,right =if (payType==1)R.mipmap.xuanzhong_1 else R.mipmap.rbtn_green_normal)
            find<TextView>(R.id.tv_zfb).setDrawable(left = R.mipmap.zhifubao,right =if (payType==2)R.mipmap.xuanzhong_1 else R.mipmap.rbtn_green_normal)
        }
    }

    private fun initText(str:String, start:Int, end:Int):CharSequence= SpanBuilder(str).size(start, end, 16).color(app, start, end, R.color.color_222222).build()


    private fun pay(payType: Int) {
        when (payType) {
            0-> balancePay()
            1-> getPayInfo(1)
            2-> getPayInfo(2)
        }
    }

    /**
     * 2微信3支付宝
     */
    private fun getPayInfo(type: Int) {
        if (type == 2) {
            TPayUtil.initWeChatPay(this.context, Const.KEY.WECHAT_APP_ID)
            if (!TPayUtil.checkSupportWeChat(this.context)) {
               showToast("请先安装微信！或选择其他支付方式！")
                return
            }
        }
        if (type == 3) {
            if (!TPayUtil.checkAliPayState(context)) {
                showToast("请先安装支付宝！或选择其他支付方式！")
                return
            }
        }
        HttpManager.payinfo(type.toString(), orderID)
                .requestSucceed(this) {
                    if (type == 2) {
                        TPayUtil.weChatPay(this@PayWindow.context, JSONObject(it.toString()))
                    }
                    if (type == 3) {
                        val get = it.get("orderInfo")
                        if (get == null) {
                            showToast("获取支付信息失败!")
                            return@requestSucceed
                        }
                        TPayUtil.aliPay(this@PayWindow.context, get.asString,  function)
                    }
                }
    }

    private fun balancePay() {
        HttpManager.balancePay(orderID)
                .request(this) {
                    if (it == null) {
                        return@request
                    }
                    if (it.code != 0) {
                        showToast(it.msg)
                        return@request
                    }
                    if (it.data == null) {
                        showToast("支付出错")
                        return@request
                    }
                    val type = it.data!!.get("type").asInt
                    ok(0,type)
                }

    }

    /**
     * 支付宝支付返回的数据
     */
    private val function: (MutableMap<String, String>) -> Unit = {
        val resultStatus = PayResult(it).resultStatus
        do {
            // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
            if (TextUtils.equals(resultStatus, "9000")) {
                ok(0,-1)
                break
            }
            // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
            if (TextUtils.equals(resultStatus, "8000")) {
                ok(3,-1)
                break
            }
            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
            ok(1,-1)
            break
        } while (false)

    }

    override fun dismiss() {
        super.dismiss()
        if (dismissByBack) {
            back.invoke(2,-1)
        }
    }

    /**
     * code:0成功1失败2取消3.确认中
     * type:1=派单流程 订单直接给司机了的。2=推单流程 推给所有司机
     */
    private fun ok(code: Int, type: Int) {
        back.invoke(code,type)
        dismissByBack=false
        dismiss()
    }
}